#!/bin/bash

readonly IS_FUSION=true
readonly DB_RELEASE_DATE="*"
readonly DB_RELEASE_VERSION="1.1.0"
readonly WORKSPACE_DIR="*"
readonly COMMON_DIR="*"

umask 0022

function getParam()
{
    # node param
    hostIp="*"
    hostName="*"
    hostPort="*"

    # user param
    dbInitUser="*"
    dbInitGroup="*"

    # db param
    dbName="*"
    dbUser="*"

    # path param
    homePath="/home/$dbInitUser"
    installPath="$WORKSPACE_DIR/dbinstall"
    pkgPath="$WORKSPACE_DIR/pkg"
    envPath="$homePath/gauss_env_$DB_RELEASE_DATE"
    xmlPath="$homePath/openGauss$DB_RELEASE_DATE.xml"
    dnPath="$installPath/cluster/dn1"

    # password param
    # according to the security redline requirements, you should inject 
    # [userPasswd, rootPasswd, dbPasswd] in jenkins environment variables

    # system param
    systemArch=`uname -p`
    systemName=`cat /etc/os-release | grep '^ID=".*' | grep -o -E '(openEuler|centos)'`
}

function clearEnv()
{
    print_log "Start clear env."
    
    checkFileExists $envPath
    if [ $? -eq 0 ]
    then
        su - $dbInitUser << EOF
        source $envPath
        gs_uninstall --delete-data
EOF
    fi

    if [ $? -ne 0 ]
    then
        return 1
    fi

    rm -rf $installPath && mkdir $installPath
    rm -rf $envPath $xmlPath

    return 0
}

function print_log()
{
    local message=$1

    echo `date +"%Y-%m-%d %H:%M:%S"` ": $message"
}

function checkFileExists()
{
    if [ ! -e $1 ]
    then
        return 1
    else
        return 0
    fi
}

function getOpenGaussPkg()
{
    rm -rf $pkgPath && mkdir $pkgPath
    chown -R $dbInitUser:$dbInitGroup $pkgPath

    # check openGauss install pkg in WORKSPACE_DIR
    if [ "`find $WORKSPACE_DIR -maxdepth 1 -regex ".*/openGauss-${DB_RELEASE_VERSION}-${systemName}-64bit\(-all\)?.tar.gz"`" == "" ]
    then

        # download openGauss install pkg in ftp server
        if [ "$systemName" == "openEuler" ] && [ "$systemArch" == "aarch64" ]
        then
            url="ftp://10.244.62.232/latest/community/OpenEulor2.0/openGauss_${DB_RELEASE_VERSION}_PACKAGES_RELEASE.tar.gz"
        elif [ "$systemName" == "openEuler" ] && [ "$systemArch" == "x86_64" ]
        then
            url="ftp://10.244.62.232/latest/community/OpenEulor2.0_X86/openGauss_${DB_RELEASE_VERSION}_PACKAGES_RELEASE.tar.gz"
        elif [ "$systemName" == "centos" ] && [ "$systemArch" == "x86_64" ]
        then
            systemName="CentOS"
            url="ftp://10.244.62.232/latest/community/CentOS7.6/openGauss_${DB_RELEASE_VERSION}_PACKAGES_RELEASE.tar.gz"
        else
            print_log "We only support CentOS+x86, openEuler+arm and openEuler+x86 by now."
            return 1
        fi

        wget $url --timeout=30 --tries=3 -P $pkgPath >& /dev/null

        if [ $? -ne 0 ]
        then
            print_log "Can not found openGauss install pkg local, and wget failed."
            return 1
        else
            print_log "Wget openGauss pkg success."
        fi

        tar -zxf "$pkgPath/openGauss_${DB_RELEASE_VERSION}_PACKAGES_RELEASE.tar.gz" -C $pkgPath
        tar -zxf  "$pkgPath/openGauss-${DB_RELEASE_VERSION}-${systemName}-64bit-om.tar.gz" -C $pkgPath

    else

        # use local openGauss install pkg. 
        # Attention: this only support pkg which is download in www.openGauss.org
        if $IS_FUSION
        then
            cp "$WORKSPACE_DIR/openGauss-${DB_RELEASE_VERSION}-${systemName}-64bit-all.tar.gz" $pkgPath/
            tar -zxf "$pkgPath/openGauss-${DB_RELEASE_VERSION}-${systemName}-64bit-all.tar.gz" -C $pkgPath
            tar -zxf "$pkgPath/openGauss-${DB_RELEASE_VERSION}-${systemName}-64bit-om.tar.gz" -C $pkgPath
        else
            cp "$WORKSPACE_DIR/openGauss-${DB_RELEASE_VERSION}-${systemName}-64bit.tar.gz" $pkgPath/
            tar -zxf "$pkgPath/openGauss-${DB_RELEASE_VERSION}-${systemName}-64bit.tar.gz" -C $pkgPath
        fi
    fi

    return 0
}

function generateXmlFile()
{
    su - $dbInitUser -c "sh $COMMON_DIR/autoXml.sh $dbInitUser $hostPort '${hostIp[*]}' '${hostName[*]}' $installPath $xmlPath"

    if [ $? -ne 0 ]
    then
        return 1
    fi

    return 0
}

function installOpenGauss()
{   
    print_log "Start install openGauss."
    
    mkdir -p $installPath
    chown -R 755 $installPath
    chown -R $dbInitUser:$dbInitGroup $installPath

    scriptPath="$pkgPath/script"

    export LD_LIBRARY_PATH=$scriptPath/gspylib/clib:$LD_LIBRARY_PATH

    if [ ${#hostname[*]} -gt 1 ];
    then
        $COMMON_DIR/autoPreInstallScript $dbInitUser $dbInitGroup $xmlPath $envPath $scriptPath $rootPasswd $userPasswd
    else
        $scriptPath/gs_preinstall -U $dbInitUser -G $dbInitGroup -X $xmlPath --sep-env-file=$envPath -L
    fi
    
    if [ $? -ne 0 ]
    then
        print_log "Preinstall openGauss failed."
        return 1
    else
        print_log "Preinstall openGauss success."
    fi

    su - $dbInitUser << EOF
    source $envPath
    $COMMON_DIR/autoInstallScript $userPasswd $xmlPath
EOF
    
    if [ $? -ne 0 ]
    then
        return 1
    fi
    
    return 0
}

function modifyProfile()
{
    modifyString=$1
    echo "set $modifyString"
    echo $modifyString >> $dnPath/postgresql.conf
}

function configOpenGauss()
{
    # use this function to write param in the postgresql.conf
    #modifyProfile "* = *"
    
    su - $dbInitUser << EOF
    source $envPath

    gsql -d postgres -p $hostPort -r -c "
    create database $dbName;
    create user $dbUser identified by '$dbPasswd';
    grant all privileges to $dbUser;"
    
    sed -i "92i host all all $hostIp/32 sha256" $dnPath/pg_hba.conf

    gs_om -t stop && gs_om -t start
EOF
    
    if [ $? -ne 0 ]
    then
        return 1
    fi
    
    return 0
}

function main()
{
    # get install param
    getParam

    # uninstall db and clear env
    clearEnv
    if [ $? -ne 0 ]
    then
        print_log "Clear env failed."
        return 1
    else
        print_log "Clear env success."
    fi
    
    # tar openGauss pkg (support 1.0.x and 1.1.0)
    getOpenGaussPkg
    if [ $? -ne 0 ]
    then
        print_log "Get pkg failed."
        return 1
    else
        print_log "Get pkg success."
    fi

    # generate xml file which is used in OM tools
    generateXmlFile
    if [ $? -ne 0 ]
    then
        print_log "Generate xml failed."
        return 1
    else
        print_log "Generate xml success."
    fi

    # install openGauss
    installOpenGauss
    if [ $? -ne 0 ]
    then
        print_log "Install openGauss failed."
        return 1
    else
        print_log "Install openGauss success."
    fi
    
    # config openGauss
    configOpenGauss
    if [ $? -ne 0 ]
    then
        print_log "config openGauss failed."
        return 1
    else
        print_log "config openGauss success."
    fi
    
    return 0
}

main $@
exit $?
